<template>
    <div class="components_edit_modal">
        <el-dialog title="编辑课程考核方案" :visible.sync="state" :show-close="true" :close-on-click-modal="false">
            <el-form :model="form" :rules="rules" ref="form">
                <el-form-item label="学校：" >
                    {{form.schoolName}}
                </el-form-item>
                <el-form-item label="学院：">
                    {{form.secondSchoolName}}
                </el-form-item>
                <el-form-item label="所属专业：" >
                    {{form.professionName}}
                </el-form-item>
                <el-form-item label="所授课程：" >
                    {{form.courseName}}
                </el-form-item>


                <el-form-item label="考核内容：" prop="content" class="lineblock textareaBox">
                    <el-input
                        type="textarea"
                        :autosize="{ minRows: 2, maxRows: 4}"
                        placeholder="请输入考核内容"
                        v-model="form.content">
                    </el-input>
                </el-form-item>
                <br>
                    <el-form-item label="考核要求：" prop="requirement" class="lineblock textareaBox">
                        <el-input
                            type="textarea"
                            :maxlength="1000"
                            :autosize="{ minRows: 2, maxRows: 4}"
                            placeholder="请输入考核要求"
                            v-model="form.requirement">
                        </el-input>
                    </el-form-item>
                <br>
                    <el-form-item label="备注：" class="lineblock textareaBox">
                        <el-input
                            type="textarea"
                            :maxlength="500"
                            :autosize="{ minRows: 2, maxRows: 4}"
                            placeholder="请输入备注"
                            v-model="form.remark">
                        </el-input>
                    </el-form-item>
                <br>
                    <el-form-item label="成绩配比：" class="lineblock scrollBarX">
                        <el-table :data="form.detailList" style="width: 100%" show-summary :summary-method="getSummaries" class="components_edit_tables bordright">
                            <el-table-column prop="scoreTypeText" label="考核项" align="center" header-align="center">
                            </el-table-column>

                            <el-table-column label="占比(%)" align="center" header-align="center">
                                <template slot-scope="scope">
                                    <el-input-number v-model="form.detailList[scope.$index].scorePercent" :min="0" :max="100" size="mini">
                                    </el-input-number>
                                </template>
                            </el-table-column>

                            <el-table-column  label="备注说明" header-align="center">
                                <template slot-scope="scope">
                                    <el-input v-model="form.detailList[scope.$index].remark" :maxlength="500">
                                    </el-input>
                                </template>
                            </el-table-column>
                        </el-table>

                    </el-form-item>

            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="save" size="small">保 存 草 稿</el-button>
                <el-button type="primary" @click="submit" size="small">提 交</el-button>
                <el-button @click="state = false" size="small">关 闭</el-button>
            </div>

        </el-dialog>

        <!-- 流程相关 -->
        <flow-init ref="courseFlow">
        </flow-init >
    </div>
</template>

<script>
    import {enums} from '@/constant'
    import { mapGetters } from 'vuex'
    export default {
        components: {

        },
        data() {
            return {
                 // state: false,
                 courseAssessmentId: null,
                 rules: {
                    grade: [
                        { required: true, message: '请选择年级', trigger: 'change', type: 'string'},
                    ],
                    content: [
                        { required: true, message: '请填写考核内容', trigger: 'blur', type: 'string'},

                    ],
                    requirement: [
                        { required: true, message: '请填写考核要求', trigger: 'blur', type: 'string'},
                    ],
                    attachment: [
                        { required: true, message: '请选择上传附件', trigger: 'change', type: 'array'},
                    ],
                 },
                form: {
                    id: null,
                    trainPlanId: null,
                    schoolId:null,
                    schoolName: null,
                    secondSchoolId:null,
                    secondSchoolName: null,
                    professionId:null,
                    professionName:null,
                    grade:null,
                    courseNo:null,
                    courseName:null,
                    content:null,
                    requirement:null,
                    remark:null,
                    detailList:[],
                },
                // 课程列表
                courseList: null,
                // 成绩类型列表
                scoreTypeList:null,

            }
        },
        created() {},
        mounted() {},
        computed:{
            state: {
                get: function () {
                    if(this.$store.getters.getCourseAssessmentSchemeEdit.state == true){
                        // 重置字段和校验
                        this.$nextTick(function(){
                            this.$refs['form'].resetFields();
                        })
                        let data = this.$store.getters.getCourseAssessmentSchemeEdit.data;
                        this.courseAssessmentId = data.courseAssessmentScheme.id;
                        // 根据id查询课程考核方案信息
                        this.getCourseAssessmentSchemeInfo();
                    }
                    return this.$store.getters.getCourseAssessmentSchemeEdit.state;
                },
                set: function (v) {
                   if(!v){
                        this.$store.commit("COURSE_ASSESSMENT_SCHEME_EDIT", {dialogState: v, data: null});
                   }
                }
            }
        },
        methods: {
            // 根据主键id查询课程考核方案信息
            getCourseAssessmentSchemeInfo(){
                let vm = this;
                vm.axios.get(api.courseAssessmentScheme.queryById + vm.courseAssessmentId).then((response) => {
                    if (response.data.success) {
                        vm.form = JSON.parse(JSON.stringify(response.data.data));
                    } else {
                        vm.$message.error(response.data.msg);
                    }
                })
            },
            getScoreType(){
                let vm = this;
                vm.axios.get(api.dictsTypesSubListUrl, {
                     params: {
                        type: "assessment_score_type",
                    }
                }).then((response) => {
                    if (response.data.success) {
                        this.scoreTypeList = JSON.parse(JSON.stringify(response.data.data));
                    } else {
                        vm.$message.error(response.data.msg);
                    }
                })
            },
            // 保存
            save() {
                let vm = this;
                vm.$refs['form'].validate((valid) => {
                    if (valid) {
                        // 校验数据
                        let scorePercentTotal = vm.form.detailList.reduce((curr, item)=>{
                            return curr + Number(item.scorePercent);
                        }, 0)
                        if(scorePercentTotal > 100){
                            vm.$message({
                                type: 'warn',
                                message: '成绩占比总和不能大于100%',
                            });
                            return;
                        }
                        // 组装数据
                        let model = {
                            id: vm.courseAssessmentId,
                            content: vm.form.content,
                            requirement: vm.form.requirement,
                            remark: vm.form.remark,
                            detailList : vm.form.detailList,
                        };
                       // console.log(model);
                       // return;
                        vm.axios.put(api.courseAssessmentScheme.update ,model)
                        .then((response) => {
                            if (response.data.success) {
                                vm.$message({
                                    type: 'success',
                                    message: response.data.msg,
                                });
                                // 关闭弹出窗口
                                vm.state = false;
                                // 刷新table
                                vm.$parent.$refs.courseAssessmentTable.$emit('vuetable:refresh');
                            } else {
                                vm.$message.error(response.data.msg);
                            }
                        })
                    } else {
                        return false;
                    }
                });
            },
             // 提交 发起流程
            submit() {
                let vm = this;
                let flowSubject = this.form.schoolName + "-" + this.form.secondSchoolName + "-"
                                    + this.form.professionName + "-" + this.form.grade + "级";
                vm.$refs['form'].validate((valid) => {
                    if (valid) {
                        // 校验数据
                        let scorePercentTotal = vm.form.detailList.reduce((curr, item)=>{
                            return curr + Number(item.scorePercent);
                        }, 0)
                        if(scorePercentTotal > 100){
                            vm.$message({
                                type: 'warn',
                                message: '成绩占比总和不能大于100%',
                            });
                            return;
                        }
                        // 组装数据
                        let model = {
                            id: vm.courseAssessmentId,
                            content: vm.form.content,
                            requirement: vm.form.requirement,
                            remark: vm.form.remark,
                            detailList : vm.form.detailList,
                        };
                        // console.log(model);
                        // return;
                        //  打开流程定义界面
                        // vm.$refs.courseFlow.showDialog(flowSubject , `jx_course_assessment_scheme`, model.id, model, api.courseAssessmentScheme.update);
                        let data = {
                                actionType: "update",
                                flowSubject: flowSubject,
                                businessCode: `jx_course_assessment_scheme`,
                                businessId: model.id,
                                businessForm: model,
                                businessUrl: api.courseAssessmentScheme.update
                        };
                        vm.$store.commit(`FLOW_INIT`, {"dialogState": true, "data": data});
                    } else {
                        return false;
                    }
                });
            },
             // 表格合计列
            getSummaries(params){
                let vm = this;
                const { columns, data } = params;
                const sums = [];
                columns.forEach((column, index) => {
                    if (index === 0) {
                        sums[index] = '合计';
                        return;
                    }else if(index == 1){
                        const values = vm.form.detailList.map(item => Number(item.scorePercent));
                        if (!values.every(value => isNaN(value))) {
                            sums[index] = values.reduce((prev, curr) => {
                                const value = Number(curr);
                                if (!isNaN(value)) {
                                    return prev + curr;
                                } else {
                                    return prev;
                                }
                            }, 0);
                            // sums[index] += ' 元';
                        }
                    }else {
                        sums[index] = '';
                    }
                })
                return sums;
            }
        },
    };
</script>
<style>
</style>